<?php

namespace app\api\controller;


use app\api\model\AnswerModel;
use app\api\model\InfoTypeModel;
use app\api\model\InfoTypeRecord;
use app\api\model\QuestionModel;
use app\api\model\SubjectModel;
use app\api\model\UserInfoModel;
use app\api\model\Rexam as RexamModel;
use app\common\controller\Api;

class Rexam extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /*
     * 问卷列表
     */

    public function subjectList()
    {

        $tags = SubjectModel::where(['is_show' => 1])->group('tag')->column('tag');

        $list = [];

        $list['每日问卷'][] = [
            'id' => 0,
            'name' => '每日问卷'
        ];

        foreach ($tags as $val) {

            $list[$val] = SubjectModel::where(['tag' => $val])->order('weigh desc')->select();

        }

        foreach ($list as $key => &$val) {

                foreach ($val as &$item){
                    $check = AnswerModel::get(['day'=>date('Y-m-d',time()),'user_id'=>$this->auth->id,'is_take'=>1,'type_id'=>$item['id']]);
                    if($check){
                        $item['is_daka'] = 1;
                    }else{
                        $item['is_daka'] = 0;
                    }
                }

            }

        $this->success('请求成功', $list);

    }


    /*
     * 问卷列表
     */
    public function questionList()
    {
        $id = input('post.id');

        if ($id == 0) {
            $answer = AnswerModel::where(['user_id' => $this->auth->id, 'is_take' => 1])->column('rexamquestion_ids');
            $arr = [];
            foreach ($answer as $val) {
                $ar = explode(',', $val);
                $arr = array_merge($ar, $arr);
            }
            $arr = array_unique($arr);
            $list = [];
            $typeList = SubjectModel::where(['is_show' => 1])->column('id');
            foreach ($typeList as $key => $val) {
                $question = QuestionModel::where(['rexam_subject_id' => $val])->where('id', 'not in', $arr)->limit(2)->select();

                if (!empty($question)) {
                    $list[] = $question;
                }
            }
            if (empty($list)) {
                $this->error('暂无数据，请联系管理员录入新的问卷');
            }
            $this->success('请求成功', $list);
        }

        $list = QuestionModel::where(['rexam_subject_id' => $id])->select();

        $this->success('请求成功', $list);
    }


    /*
     * 健康笔记日期列表
     */
    public function healthDayList()
    {
        $list = RexamModel::where(['user_ids'=>$this->auth->id,'status'=>'normal'])->column('id,day,is_read');

        $this->success('请求成功',$list);

    }

    /*
     * 健康笔记问题列表
     */
    public function healthQuestionList()
    {
        $id = input('post.id');

        if(!$id){
            $this->error('请传入id');
        }
        RexamModel::where('id',$id)->update(['is_read'=>2]);

        $check = AnswerModel::get(['rexam_id'=>$id]);

        if($check){
            $this->success('请求成功', $check);
        }

        $rexamDetail = RexamModel::get($id);

        $list = QuestionModel::where(['id' => ['in',$rexamDetail['rexam_question_ids']]])->select();

        foreach ($list as &$val){
            $val['rexam_id'] = $id;
        }
        $this->success('请求成功', $list);
    }

    /*
     * 答题
     * [{"qid":5,"ans":"B","res":1},{"qid":1,"ans":"A","res":0},{"qid":6,"ans":"0","res":0},{"qid":2,"ans":"A","res":0},{"qid":7,"ans":"0","res":1}]
     */
    public function goQuestion()
    {
        $answer = input('post.answer');
        $rexam_id = input('post.rexam_id');
        $is_take = input('post.is_take', 0);
//        $type = input('post.type');
        $id = input('post.id', 0);

//        if (empty($type)) {
//            $this->error('请传入问卷类型');
//        }
        //$info = QuestionModel::get($param['id']);
        if (empty($answer)) {
            $this->error('答案不能为空');
        }
//        $answer = '[{"qid":5,"ans":"B","res":1},{"qid":1,"ans":"A","res":0},{"qid":6,"ans":"0","res":0},{"qid":2,"ans":"A","res":0},{"qid":7,"ans":"0","res":1}]';
//        $answer = '[{"qid":8,"ans":"19","res":1}]';

        $answer = html_entity_decode($answer);
        $answer = json_decode($answer, true);

        $data = [];
        $data['user_id'] = $this->auth->id;
        $data['question_count'] = count($answer);
        $data['rexam_id'] = $rexam_id;
        $data['right_count'] = 0;
        $data['points'] = 0;
        $data['is_take'] = $is_take;
        $data['type_id'] = 7;
        $data['answerjson'] = json_encode($answer);
        $data['day'] = date('Y-m-d', time());
        foreach ($answer as $key => $val) {
            $question = QuestionModel::get($val['qid']);
            if (!$question) {
                $this->error('当前问卷中包含已经删除的问卷内容');
            }

            if (!empty($question['info_id']) || $data['is_take'] > 0) {
                //答卷关联身体指数
//                $userInfoDetail = UserInfoModel::get(['user_id' => $this->auth->id, 'type_id' => $question['info_id']]);

//                if (!$userInfoDetail) {
                    $infoDetail = InfoTypeModel::get($question['info_id']);
                    $infoData = [
                        'day' =>  $data['day'],
                        'user_id' => $this->auth->id,
                        'type_id' => $question['info_id'],
                        'type_value' => $val['ans']
                    ];
                    $infoData['company'] = $infoDetail['company'];
                    $userInfoModel = new InfoTypeRecord();

                    $userInfoModel->allowField(true)->data($infoData);
                    $userInfoModel->save();
//                } else {
//                    $userInfoDetail->type_value = $val['ans'];
//                    $userInfoDetail->save();
//                }
            }
            if ($val['res'] == 1) {
                $data['right_count']++;
                $data['points'] += $question['score'];
            }
            if ($key == 0) {
                $data['rexamquestion_ids'] = $val['qid'];
            } else {
                $data['rexamquestion_ids'] .= ',' . $val['qid'];
            }
        }

        if ($id > 0) {
            $model = AnswerModel::get($id);

            if (!$model) {
                $model = new AnswerModel();
            }else{
                $answer_arr = json_decode($data['answerjson'],true);
                foreach ($model['answerjson'] as $val){
                    $res = 0;
                    foreach ($answer_arr as $v){
                        if($v['qid'] == $val['qid']){
                            $res = 1;
                        }
                    }
                    if($res == 0){
                        $answer_arr[] = [
                            'qid'=>$val['qid'],
                            'ans'=>$val['ans'],
                            'res'=>0,
                        ];
                    }
                }
                $data['answerjson'] = json_encode($answer_arr);
            }
        } else {
            $model = new AnswerModel();
        }
        $model->allowField(true)->data($data);
        $model->save();

        $this->success('提交成功');

    }

    /*
     * 获取答题记录
     */

    public function myAnswerQuestion()
    {
        $is_take = input('post.is_take', 0);
        $type = input('post.type');
        $answer = AnswerModel::get(['user_id' => $this->auth->id, 'type_id' => $type, 'day' => date('Y-m-d', time())]);
        $this->success('请求成功', $answer);
    }

    /*
     * 问卷报告类型列表
     */
    public function myZhuanReport()
    {
        $model = new AnswerModel();

        $list = $model->where(['user_id' => $this->auth->id, 'is_show' => 1])->field('id,day,user_id')->select();

        $this->success('请求成功', $list);
    }

    /*
     * 专项问卷列表
     */
    public function myZhuanReportList()
    {
        $id = input('post.id');

        $model = new AnswerModel();

        $data = $model::get($id);
        $this->success('请求成功', $data);
    }


}